import allure
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

from homework.web.config.base_data import debugger_address, browser
from homework.web.utils.log import log


class BasePage:
    def __init__(self, driver: WebDriver = None):
        if driver is not None:
            self.driver = driver
        else:
            # 第一次打开浏览器
            self.open_browser(browser)

    def find(self, by, value):
        WebDriverWait(self.driver, 10) \
            .until(expected_conditions.visibility_of_element_located(
            (by, value)
        ))
        allure.attach(body = self.driver.get_screenshot_as_png(), attachment_type = allure.attachment_type.PNG)
        return self.driver.find_element(by, value)

    def click(self, by, value):
        self.find(by, value).click()

    def send_keys(self, by, value, keyword):
        self.find(by, value).send_keys(keyword)

    # 检查元素是否存在
    def is_element_exsist(self, by, value):
        try:
            self.find(by, value)
            return True
        except Exception as e:
            return False

    # 检查元素的子元素是否存在
    def is_child_element_exsist(self, element: WebElement, by, value):
        try:
            element.find_element(by, value)
            return True
        except Exception as e:
            return False

    def open_browser(self, browser):
        if browser == 'chrome':
            chrome_options = ChromeOptions()
            chrome_options.debugger_address = debugger_address
            self.driver = webdriver.Chrome(options = chrome_options)
        elif browser == 'firefox':
            firefox_options = FirefoxOptions()
            firefox_options.debugger_address = debugger_address
            self.driver = webdriver.Firefox(options = firefox_options)
        else:
            chrome_options = ChromeOptions()
            chrome_options.debugger_address = debugger_address
            self.driver = webdriver.Chrome(options = chrome_options)